
package com.cmsz.paydemo.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @TODO ADD REASON
 * @Date 2017年4月29日 下午4:15:54
 * @author Edison_lv
 * @version
 */
public class SimpleHttpServer2 {
	private int port = 8081;
	private ServerSocketChannel serverSocketChannel = null;
	private ExecutorService executorService;
	private static final int POOL_MULTIPLE = 4;

	public SimpleHttpServer2() throws IOException {
		executorService = Executors.newFixedThreadPool(
				Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);
		serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.socket().setReuseAddress(true);
		serverSocketChannel.socket().bind(new InetSocketAddress(port));
		System.out.println("服务端启动成功");
	}

	public void service() {
		while (true) {
			SocketChannel socketChannel = null;
			try {
				socketChannel = serverSocketChannel.accept();
				executorService.execute(new Handler(socketChannel));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String args[]) throws IOException {
		new SimpleHttpServer2().service();
	}

	class Handler implements Runnable {
		private SocketChannel socketChannel;

		public Handler(SocketChannel socketChannel) {
			this.socketChannel = socketChannel;
		}

		public void run() {
			handle(socketChannel);
		}

		public void handle(SocketChannel socketChannel) {
			try {
//				Socket socket = socketChannel.socket();
				/*System.out.println("客户端信息：" + socket.getInetAddress() + ":"
						+ socket.getPort());*/

				ByteBuffer buffer = ByteBuffer.allocate(2048);
				socketChannel.read(buffer);
				buffer.flip();
				String request = decode(buffer);
				System.out.println("异步结果通知报文数据："+request);
				Boolean siganFlag = SignUtil.checkSign(request);
				System.out.println("异步结果通知报文签名结果："+siganFlag);
				//服务器返回数据
				String rspData = FileUtil.getData("refundNotifyRspData.xml");
				rspData = SignUtil.sign(rspData);
				socketChannel.write(encode(rspData));
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (socketChannel != null)
						socketChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		private Charset charset = Charset.forName("UTF-8");

		public String decode(ByteBuffer buffer) {
			CharBuffer charBuffer = charset.decode(buffer);
			return charBuffer.toString();
		}

		public ByteBuffer encode(String str) {
			return charset.encode(str);
		}
	}
}
